import { isReferee } from "@/func";
import { Player } from "@minecraft/server";
import { Dimensions } from "@sapi-game/constants";
import { Game, GameComponent } from "@sapi-game/main";
import { DimensionIds, EntityTypeIds } from "@sapi-game/utils/vanila-data";
import { KcpdGames, KcpdTimes } from "./games";
import { KcpdBackState } from "./kcpdBack";
import { KcpdFuncs } from "../func";

export class KcpdGameStarter extends GameComponent<KcpdBackState> {
    private readonly gamePos = {
        x: -143,
        y: -53,
        z: -362,
    };

    private readonly timePos = {
        x: -145,
        y: -53,
        z: -362,
    };

    override onAttach(): void {
        this.subscribe(
            Game.events.buttonPush,
            (e) => {
                const player = e.source as Player;
                if (!isReferee(player)) {
                    player.sendMessage("你不是裁判，无权开始");
                    return;
                }
                this.start(player);
            },
            {
                loc: [-146, -52, -365],
                dimensionId: DimensionIds.Overworld,
                sourceType: EntityTypeIds.Player,
            }
        );
    }

    /**开始游戏 */
    start(player: Player) {
        const size = this.state.players.validSize;
        if (size < 2) return player.sendMessage("人数过少，无法开始");
        const game = this.getGame();
        const time = this.getTime();
        if (game && time) {
            try {
                game.onStart(
                    this.state.players.getAllPlayers().filter((p) => p.isValid),
                    time
                );
            } catch (err) {
                player.sendMessage("游戏开始失败" + err);
                return;
            }
            this.state.players.clear();
            //还在的人直接传送回去
            this.state.region.forEachPlayer((p) => {
                KcpdFuncs.hub(p);
            });
        } else {
            player.sendMessage("§c无法获取游戏或游戏时间");
        }
    }

    /**通过红石信号获取选择的游戏 */
    getGame() {
        const power = Dimensions.Overworld.getBlock(
            this.gamePos
        )?.getRedstonePower();
        if (!power) return;
        const game = KcpdGames.find((g) => g.power >= power);
        return game;
    }

    /**通过红石信号获取选择的时间 */
    getTime() {
        const power = Dimensions.Overworld.getBlock(
            this.timePos
        )?.getRedstonePower();
        if (!power) return;
        const time = KcpdTimes.find((t) => t.power >= power);
        return time?.time;
    }
}
